package com.liveneo.adapter.mobile.web.controller;

import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.liveneo.adapter.base.entity.PrpmAppVersion;
import com.liveneo.adapter.base.entity.PrpmMobileModel;
import com.liveneo.adapter.base.entity.PrpmPre;
import com.liveneo.adapter.base.support.AdapterConstants;
import com.liveneo.adapter.base.support.BaseController;
import com.liveneo.adapter.base.support.LogUtils;
import com.liveneo.adapter.mobile.model.dto.MobileVersionDto;
import com.liveneo.adapter.mobile.model.request.VersionRequest;
import com.liveneo.adapter.mobile.model.response.VersionResponse;
import com.liveneo.adapter.mobile.service.MobileAppVersionService;
import com.liveneo.adapter.mobile.service.MobileModelService;
import com.liveneo.adapter.mobile.service.PrpmAppVersionService;
import com.liveneo.adapter.mobile.service.PrpmPreService;
import com.liveneo.adapter.mobile.support.MobileReturnCodeSupport;
import com.liveneo.adapter.mobile.util.DateUtil;
import com.liveneo.adapter.mobile.util.Str;
import com.liveneo.adapter.mobile.util.UUIDUtils;
import com.liveneo.system.base.utils.DateUtils;
import com.liveneo.system.base.utils.EncryptUtil;
import com.liveneo.system.base.utils.JsonUtils;

@Controller
@RequestMapping("/mobile")
public class MobileVersionController extends BaseController {
    @Autowired
    private MobileAppVersionService mobileAppVersionService;
    @Autowired
    private MobileModelService      mobileModelService;
    @Autowired
    private PrpmAppVersionService   prpmAppVersionService;
    @Autowired
    private PrpmPreService          prpmPreService;

    // @RequestMapping("getVersion.action")
    // @ResponseBody
    // public String getVersion(@ModelAttribute(AdapterConstants.MOBILE_REQUEST_PARAM_NAME) String data) {
    // VersionRequest request = JsonUtils.fromJsonWithBase64(data, VersionRequest.class);
    // LogUtils.debug("手机版本检查，传入参数：" + request);
    // VersionResponse baseResponse = null;
    // String result = "";
    // try {
    // PrpmAppVersion version = mobileAppVersionService.getVersion(request);
    // if (version == null) {
    // baseResponse =
    // MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_ERR_PARAM,MobileReturnCodeSupport.SYS_CODE,
    // MobileReturnCodeSupport.CODE_ERR_PARAM_NO_EXISTS, VersionResponse.class);
    // } else {
    // MobileVersionDto dto = new MobileVersionDto();
    // dto.setUuid(version.getVersionId());
    // dto.setAppType(version.getAppType());
    // BeanUtils.copyProperties(dto, version);
    // // TODO 假数据去除
    // dto.setUuid(version.getVersionId());
    // dto.setCodeType("codeType");
    // dto.setCodeName("codeName");
    // dto.setUpdateTime("2016-06-22 15:58:29");
    // dto.setVersionId("1");
    // dto.setCreateDate("2016-06-22 15:58:29");
    // dto.setUptPkgFile("更新包名称");
    // dto.setDownloadUrl("http://www.test.com/download");
    // dto.setVersionConten("versionContent");
    // dto.setEffectDate("2016-06-22 15:58:29");
    // dto.setAppType("2");
    // dto.setSystemCode("1");
    // dto.setValidStatus("1");
    // dto.setMandatoryUpgrade("2");
    // dto.setCodeCode("codeCode");
    // // TODO 从OSS云上获取下载地址
    // // String appUrl = ossManagerTool.getImgURl(version.getDownloadUrl());
    // // String appType = request.getAppType();
    // // if ("1".equals(appType)) {
    // // StringBuffer url = new StringBuffer();
    // // url.append("https");
    // // url.append(appUrl.substring(4,appUrl.indexOf("?")));
    // // dto.setDownloadUrl(url.toString());
    // // }else {
    // // dto.setDownloadUrl(appUrl);
    // // }
    // baseResponse =
    // MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_SUCCESS,MobileReturnCodeSupport.SYS_CODE, null,
    // VersionResponse.class);
    // baseResponse.setPrpmVersion(dto);
    // }
    // } catch (AppException e) {
    // LogUtils.error("获取手机版本出错，错误信息:", e);
    // baseResponse = MobileReturnCodeSupport.buildReponse(e.getCode(),MobileReturnCodeSupport.SYS_CODE,
    // e.getDetailCode(), VersionResponse.class);
    // } catch (Exception e) {
    // LogUtils.error("获取手机版本出错，错误信息:", e);
    // baseResponse =
    // MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_INTERNAL_ERROR,MobileReturnCodeSupport.SYS_CODE,
    // null,
    // VersionResponse.class);
    // } finally {
    // result = JsonUtils.toJson(baseResponse);
    // // 日志记录响应json
    // if (MobileReturnCodeSupport.CODE_SUCCESS.equals(baseResponse.getResultCode())) {
    // LogUtils.info("返回结果【" + result + "】");
    // } else {
    // LogUtils.error("返回结果【" + result + "】");
    // }
    // result = EncryptUtil.encodeBase64(result);
    // }
    // return result;
    // }
    /**
     * MP25
     * 1.当前客户端版本与服务端版本比较，检查是否有新版本。
     * 2.在初始化应用时调用。
     * 
     * @Title：手机版本检查
     * @author zhangyw 2016年10月12日 下午1:44:34
     * @param data
     * @return String
     */
    @RequestMapping("getNewVersion.action")
    @ResponseBody
    public String getNewVersion(@ModelAttribute(AdapterConstants.MOBILE_REQUEST_PARAM_NAME) String data) {
        String loguuid = UUIDUtils.getUUIDStr();
        String logTitle = "MP25入参=" + loguuid;
        VersionRequest request = JsonUtils.fromJsonWithBase64(logTitle, data, VersionRequest.class);
        VersionResponse response = null;
        String result = "";
        try {
            String updateType = request.getUpdateType();// 更新类型 1-更新 2-预更新
            String versionId = request.getVersionId();// 终端版本号
            String appType = request.getOs();// app类型
            String projectCode = request.getProjectCode();
            String userId = request.getUserId();
            if (StringUtils.isBlank(updateType) || StringUtils.isBlank(versionId)) {
                throw new Exception("请检查输入参数！");
            }
            if ("A".equals(projectCode)) {
                projectCode = "3";
            } else if ("B".equals(projectCode)) {
                projectCode = "2";
            } else if ("C".equals(projectCode)) {
                projectCode = "1";
            }
            PrpmAppVersion currentPrpMversion = null;
            // 更新
            if ("1".equals(updateType)) {
                currentPrpMversion = prpmAppVersionService.getVersion(versionId, appType, projectCode);
                // 预更新
            } else if ("2".equals(updateType)) {
                PrpmPre prpmPre = new PrpmPre();
                prpmPre.setUserType(projectCode);
                prpmPre.setPhoneno(userId);
                prpmPre = prpmPreService.getPrpmPreByUserId(prpmPre);
                if (prpmPre != null) {
                    currentPrpMversion = prpmAppVersionService.getPreVersion(versionId, appType, projectCode);
                }
            }
            /**
             * 现有客户端版本
             * 通过传入的versionId（终端版本号）、os（App类型1-IOS 2-Android）、systemCode（系统代码1-移动查勘 2-自助查勘）
             * 查询数据库prpm_app_version表格，获取到对应的数据库用户安装的版本信息。
             * 通过上一步查询到的用户安装版本，通过结果的EffectDate、systemCode、validStatus、
             * appType、flag五个字段信息查询（第一个字段EffectDate的判断逻辑为大于上次结果查询到的EffectDate、小于当前时间
             * 的时刻，后四个字段的判断逻辑均为等于），查询的结果按照EffectDate降序排列。
             * 照此逻辑，获取的集合如果为空，则没版本需要更新，
             * 如果集合中存在有值，则第一条记录即为最新的版本。
             */
            if (currentPrpMversion == null) {// 找不到对应的版本信息
                response = MobileReturnCodeSupport.buildReponse3(MobileReturnCodeSupport.CODE_SUCCESS, MobileReturnCodeSupport.SYS_CODE,
                        MobileReturnCodeSupport.KEY_MOBILE_00041, VersionResponse.class);
            } else {
                /** 获取有效的新版本集合 */
                List<PrpmAppVersion> validPrpMversions = prpmAppVersionService.getValidVersions(currentPrpMversion);
                if (validPrpMversions != null && validPrpMversions.size() > 0) {
                    PrpmAppVersion version = validPrpMversions.get(0);
                    MobileVersionDto prpmVersion = new MobileVersionDto();
                    prpmVersion.setUuid(version.getVersionId());// 唯一标识uuid
                    prpmVersion.setUpdateTime(DateUtils.formatDateTime(new Date()));// 更新时间
                    prpmVersion.setVersionId(version.getVersionId());// 终端版本号
                    if (version.getCreateTime() != null) {
                        prpmVersion.setCreateDate(DateUtils.formatDateTime(version.getCreateTime()));// 版本创建时间
                    }
                    prpmVersion.setUptPkgFile(version.getUptPkgFile());// 更新包文件名称
                    prpmVersion.setDownloadUrl(version.getDownLoadUrl());// 更新包下载Url
                    prpmVersion.setVersionConten(version.getVersionContent());// 版本更新内容
                    prpmVersion.setEffectDate(DateUtils.formatDateTime(version.getEffectDate()));// 生效时间
                    prpmVersion.setAppType(version.getAppType());// 终端类型1-IOS 2-Android
                    prpmVersion.setSystemCode(version.getSystemCode());// 系统代码1-移动查勘 2-自助查勘
                    prpmVersion.setValidStatus(version.getValidStatus());// 有效状态1-有效 2-无效
                    prpmVersion.setMandatoryUpgrade(version.getMandatoryUpgrade());// 更新模式1-强制更新 2-选择更新
                    // prpmVersion.setUpdateFlag(version.getFlag());// 是否需要更新
                    prpmVersion.setUpdateFlag("1"); // 0-不需要更新 1-需要更新
                    response = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_SUCCESS, MobileReturnCodeSupport.SYS_CODE,
                            MobileReturnCodeSupport.KEY_MOBILE_00015, VersionResponse.class);
                    response.setPrpmVersion(prpmVersion);
                } else {// 没有新版本
                    MobileVersionDto prpmVersion = new MobileVersionDto();
                    prpmVersion.setUuid(currentPrpMversion.getVersionId());
                    prpmVersion.setUpdateTime(currentPrpMversion.getModifyTime() == null ? "" : DateUtil.formatDate(currentPrpMversion.getModifyTime()));
                    prpmVersion.setVersionId(currentPrpMversion.getVersionId());
                    prpmVersion.setCreateDate(currentPrpMversion.getCreateTime() == null ? "" : DateUtil.formatDate(currentPrpMversion.getCreateTime()));
                    prpmVersion.setUptPkgFile(currentPrpMversion.getUptPkgFile());
                    prpmVersion.setDownloadUrl(currentPrpMversion.getDownLoadUrl());
                    prpmVersion.setVersionConten(currentPrpMversion.getVersionContent());
                    prpmVersion.setEffectDate(currentPrpMversion.getEffectDate() == null ? "" : DateUtil.formatDate(currentPrpMversion.getEffectDate()));
                    prpmVersion.setAppType(currentPrpMversion.getAppType());
                    prpmVersion.setSystemCode(currentPrpMversion.getSystemCode());
                    prpmVersion.setValidStatus(currentPrpMversion.getValidStatus());
                    prpmVersion.setMandatoryUpgrade(currentPrpMversion.getMandatoryUpgrade());
                    prpmVersion.setUpdateFlag("0");// 0-不需要更新，1-需要更新
                    response = MobileReturnCodeSupport.buildReponse(MobileReturnCodeSupport.CODE_SUCCESS, MobileReturnCodeSupport.SYS_CODE,
                            MobileReturnCodeSupport.KEY_MOBILE_00014, VersionResponse.class);
                    response.setPrpmVersion(prpmVersion);
                }
            }
        } catch (Exception e) {
            LogUtils.error("获取手机版本出错，错误信息:", e);
            response = MobileReturnCodeSupport.buildReponse2(MobileReturnCodeSupport.CODE_INTERNAL_ERROR, MobileReturnCodeSupport.SYS_CODE, "获取手机版本出错，错误信息:"
                    + e.getMessage(), VersionResponse.class);
        } finally {
            result = JsonUtils.toJson(response);
            // 日志记录响应json
            if (MobileReturnCodeSupport.CODE_SUCCESS.equals(response.getResultCode())) {
                LogUtils.info("返回结果【" + result + "】");
            } else {
                LogUtils.error("返回结果【" + result + "】");
            }
            result = EncryptUtil.encodeBase64(result);
        }
        return result;
    }

    /**
     *
     * 表中不存在数据时正常更新
     * 表中存在数据时，
     * 1.存在的匹配手机号正常更新，其它不更新
     * 2.手机号为空时不更新
     * @Title： 判断是否检测更新app版本 *
     * 
     * @author zhangyw 2016年10月21日 上午11:15:38
     * @param phoneNo
     * @return
     */
    public boolean existPhoneNo(String phoneNo) {
        if (!Str.isNotNullStr(phoneNo)) {
            return false;
        }
        List<PrpmMobileModel> prePhones = mobileModelService.queryPre();
        if (prePhones == null || prePhones.size() == 0) {
            return true;
        }
        PrpmMobileModel model = new PrpmMobileModel();
        model.setPhoneNo(phoneNo);
        if (prePhones.contains(model)) {
            return true;
        }
        return false;
    }

    /**
     * 
     * @Description:判断是否检测更新app版本
     * 表中不存在数据时正常更新
     * 表中存在数据时，
     * 	1.存在的匹配手机号正常更新，其它不更新
     * 	2.手机号为空时不更新
     * @Author:lzp
     */
    public boolean noExitPno(String phoneNo) {
        List<PrpmMobileModel> prePhones = mobileModelService.queryPre();
        if (prePhones == null || prePhones.size() == 0) {
            return false;
        }
        int len = prePhones.size();
        if (len > 0 && StringUtils.isBlank(phoneNo)) {
            return true;
        }
        for (int i = 0; i < len; i++) {
            String pno = prePhones.get(i).getPhoneNo();
            if (phoneNo.equals(pno)) {
                return false;
            }
        }
        return true;
    }
}
